package com.rbs.controller;

import com.rbs.entity.*;
import com.rbs.service.OrderItemService;
import com.rbs.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @RequestMapping("/insertOrder")
    public String insertOrder(int addressId, HttpSession session,Model model){
        User user = (User) session.getAttribute("user");
        Cart cart = (Cart) session.getAttribute("cart");
        //添加订单表
        Order order = new Order();
        order.setUser(user);
        Address address = new Address();
        address.setAddressId(addressId);
        order.setAddress(address);
        order.setOrderState(1);//创建订单时 状态一定是未支付状态 1
        order.setGoodPrice(cart.getTotalMoney());
        orderService.insertOrder(order);
        //添加订单详情表,添加多次 循环cart中的buyMap
        Map<Integer, CartItem> buyMap = cart.getBuyMap();
        Set<Map.Entry<Integer, CartItem>> entries = buyMap.entrySet();
        for (Map.Entry<Integer, CartItem> entry : entries) {
            OrderItem orderItem = new OrderItem();
            CartItem value = entry.getValue();
            orderItem.setBook(value.getBook());
            orderItem.setOrder(order);
            orderItem.setCount(value.getCount());
            orderItem.setAmount(value.getBook().getDangPrice()*value.getCount());
            orderItemService.insertOrderItem(orderItem);
        }
        model.addAttribute("order",order);
        return "/order/order_ok.jsp";
    }
    @RequestMapping("/selectByUserId")
    public String selectByUserId(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        List<Order> orders = orderService.selectByUserId(userId);
        model.addAttribute("orders",orders);
        return "forward:/order/my_order.jsp";
    }
}
